from database import Database
from host_group import HostGroup
from proxy_group import ProxyGroup


class ConnectionRules:
	def __init__(self, rule_id):
		self.id = rule_id
		self.db = Database()

		sql = "SELECT * FROM connection_rules WHERE idconnection_rules = '" + str(self.id) + "'"
		res = self.db.execute(sql)
		if res.__len__() == 0:
			print "Rule " + rule_id + " not found!"
			return False
		
		res = res[0]
		# Set src_id and src 
		self.src_id     = res['src']
		if not self.src_id:
			# Any
			self.src = HostGroup(-1L)
		else:
			self.src = HostGroup(self.src_id)

		# Set dst_id and dst 
		self.dst_id     = res['dst']
		if not self.dst_id:
			# Any
			self.dst = HostGroup(-1L)
		else:
			self.dst = HostGroup(self.dst_id)

		# Set gateway_id and gateway 
		self.gateway_id     = res['gateway']
		if not self.gateway_id:
			# Any
			self.gateway = ProxyGroup(-1L)
		else:
			self.gateway = ProxyGroup(self.gateway_id)

		if res['conntrack'] == 0:
			self.ct_enable = False
		else:
			self.ct_enable = True

		#Action: 'allow' or 'deny'
		self.action     = res['action']

		if res['log'] == 0:
			self.log = False
		else:
			self.log = True

	def match_src(self, src):	
		return self.src.match(src)

	def match_dst(self, dst):	
		return self.dst.match(dst)

	def get_proxy(self):
		return self.gateway.get_proxy()
